//
//  ManualInputViewController.m
//  e-nurse
//
//  Created by  on 12/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ManualInputViewController.h"
#import "Database.h"
#import "Record.h"
#import "Utils.h"
#import "ServerProxy.h"
#import "User.h"

@interface ManualInputViewController ()

@property (strong, nonatomic) NSDate* date;
@property (strong, nonatomic) UITextField* activeTextField;

@end

@implementation ManualInputViewController
@synthesize highPressureTextBox = _highPressureTextBox;
@synthesize lowPressureTextBox = _lowPressureTextBox;
@synthesize heartRateTextBox = _heartRateTextBox;
@synthesize hasMedicineSwitch = _hasMedicineSwitch;
@synthesize descriptionTextBox = _descriptionTextBox;
@synthesize amPMLabel = _amPMLabel;
@synthesize hourLabel = _hourLabel;
@synthesize minLabel = _minLabel;
@synthesize date = _date;
@synthesize scrollView = _scrollView;
@synthesize activeTextField = _activeField;

- (void)dealloc
{
    self.date = nil;
    self.activeTextField = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSDate* date = [[NSDate alloc] init];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[NSDate date]];
    NSInteger hour = [components hour];
    if(hour >= 0 && hour < 12)
    {
        self.hourLabel.text = [Utils formatValue:hour forDigits:2];
        self.amPMLabel.text = @"AM";
    }
    else 
    {
        self.hourLabel.text = [Utils formatValue:hour - 12 forDigits:2];
        self.amPMLabel.text = @"PM";
    }
    
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:[NSDate date]];
    self.minLabel.text = [NSString stringWithFormat:@"%2d", [components2 minute]];
    
    self.date = date;
    [date release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    self.highPressureTextBox = nil;
    self.lowPressureTextBox = nil;
    self.heartRateTextBox = nil;
    self.heartRateTextBox = nil;
    self.hasMedicineSwitch = nil;
    self.descriptionTextBox = nil;
    self.amPMLabel = nil;
    self.hourLabel = nil;
    self.minLabel = nil;
    self.scrollView = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self unregisterForKeyboardNotifications];
    [super viewWillDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)saveButtonClicked:(id)sender
{
    Record *record = [[Record alloc] initWithHighPressure:[self.highPressureTextBox.text floatValue]  
                                              lowPressure:[self.lowPressureTextBox.text floatValue] 
                                               heartRate:[self.heartRateTextBox.text intValue] takenMedicine:self.hasMedicineSwitch.isOn 
                                              description:self.descriptionTextBox.text date:self.date];

    [[Database sharedInstance] addRecord:record userId:[[ServerProxy sharedInstance] currentUserId]];
    [record release];
}

-(void)closeButtonClicked:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
 
    BOOL result = YES;
    
    if (textField == self.highPressureTextBox || textField == self.lowPressureTextBox)
    {
        result = [Utils checkFloat:newString];
    }
    else if(textField == self.heartRateTextBox)
    {
        result = [Utils checkInt:newString];
    }
    
    return result;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(self.activeTextField != nil)
    {
        [self.activeTextField resignFirstResponder];
    }
    return NO;
}


- (void)keyboardDidShow:(NSNotification*)aNotification
{
    // Step 1: Get the size of the keyboard.
    CGSize keyboardSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    // Step 2: Adjust the bottom content inset of your scroll view by the keyboard height.
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    
    // Step 3: Scroll the target text field into view.
    CGRect aRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - keyboardSize.height - 44);
    
    CGRect activeTextFieldRect = self.activeTextField.frame;
    if (!CGRectContainsPoint(aRect, CGPointMake(activeTextFieldRect.origin.x, activeTextFieldRect.origin.y + activeTextFieldRect.size.height))) {
        CGPoint scrollPoint = CGPointMake(0.0, activeTextFieldRect.origin.y + activeTextFieldRect.size.height - aRect.size.height);
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)unregisterForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.activeTextField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.activeTextField = nil;
}


@end
